package com.scs.application.core.model;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.annotation.JSONField;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.scs.application.consts.CacheConsts;
import com.scs.application.core.utils.CacheUtils;
import com.scs.application.core.utils.Reflections;
import com.scs.application.core.utils.StringUtils;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;

import java.io.Serializable;
import java.util.Date;

/**
 * ${DESCRIPTION}
 *
 */
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class DataEntity extends BaseEntity implements Serializable {

    @TableId(value = "id", type = IdType.ID_WORKER_STR)
    private String id;


    @JSONField(deserialize = false, serialize = false)
    @JsonIgnore
    @TableField(fill = FieldFill.INSERT)
    private String creator;

    @JSONField(deserialize = false)
    @TableField(fill = FieldFill.INSERT)
    private Date gmtCreate;


    @JSONField(deserialize = false)
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date gmtModified;

    @JSONField(deserialize = false)
    @JsonIgnore
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private String modifier;


    @JSONField(name = "creator", deserialize = false)
    @JsonProperty(value = "creator")
    public String getCreatorName() {
        if (StringUtils.isBlank(this.creator)) {
            return null;
        }
        return getNickname(this.creator);
    }

    @JSONField(name = "modifier", deserialize = false)
    @JsonProperty(value = "modifier")
    public String getModifierName() {
        if (StringUtils.isBlank(this.modifier)) {
            return null;
        }
        return getNickname(this.modifier);
    }

    private String getNickname(String id) {
        try {
            Object user = CacheUtils.get(CacheConsts.UPMS_USERS_ID, id);
            if (user == null) {
                return id;
            }
            // 不知道什么原因，在mscm中获取到的对象为jsonobject
            if (user instanceof JSONObject) {
                return ((JSONObject) user).getString("nickname");
            }
            Object nickName = Reflections.getFieldValue(user, "nickname");
            return nickName.toString();
        } catch (IllegalArgumentException e) {
            return id;
        } catch (Exception e) {
            return id;
        }
    }

    @JsonIgnore
    @JSONField(serialize = false,deserialize = false)
    public boolean isNewRecord(){
        return StringUtils.isBlank(id);
    }
}

